package com.example.zyl.common.query.page;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zyl.common.CommonResult;
import com.example.zyl.common.enums.CommonCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * 公共分页请求类
 *
 * @author zyl
 * @since 2023-11-06
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class PageResult<T> extends CommonResult<T> {

    /**
     * 每页长度
     */
    private Long pageSize;

    /**
     * 页索引
     */
    private Long pageIndex;

    /**
     * 数据总数
     */
    private Long totalSize;


    /**
     * 封装分页结果集
     *
     * @param page 分页参数
     * @return CommonPageResult
     */
    public static <T> PageResult<List<T>> pageResult(Page<T> page) {
        PageResult<List<T>> pageResult = new PageResult<>();
        extracted(page, pageResult);
        return pageResult;
    }


    /**
     * 封装分页结果集
     *
     * @param supplier 分页参数
     * @return CommonPageResult
     */
    public static <T> PageResult<List<T>> pageResultSupplier(Supplier<Page<T>> supplier) {
        Page<T> page = supplier.get();
        PageResult<List<T>> pageResult = new PageResult<>();
        extracted(page, pageResult);
        return pageResult;
    }


    private static <T> void extracted(Page<T> page, PageResult<List<T>> pageResult) {
        pageResult.setSuccess(true);
        pageResult.setCode(CommonCode.SUCCESS.getCode());
        pageResult.setMsg(CommonCode.SUCCESS.getMsg());
        if (page.getRecords() == null || page.getRecords().isEmpty()) {
            page.setRecords(new ArrayList<>());
        }
        pageResult.setData(page.getRecords());
        pageResult.setTotalSize(page.getTotal());
        pageResult.setPageIndex(page.getCurrent());
        pageResult.setPageSize(page.getSize());
    }

}